package com.moorecat.app;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.moorecat.MooerApplication;
import com.moorecat.R;
import com.moorecat.bean.SearchLocation;
import com.moorecat.bean.Shop;
import com.moorecat.config.Const;
import com.moorecat.http.HttpUtils;
import com.moorecat.utils.ui.ProgressLinearLayout;

/**
 * @author pengfei.xu
 * @version 创建时间：2011-6-11 下午05:18:05 类说明
 */
public class BusinessList extends Activity implements OnClickListener,
		OnItemClickListener, OnScrollListener {

	private final String TAG = "BusinessList";

	private MooerApplication mooerApp;

	private TextView title, num, rigion, type, concern;

	private ImageView rigionButton, typeButton, concernButton;

	private ListView listView;

	private ProgressLinearLayout footer;

	private BusinessAdapter adapter;

	private List<Shop> shopList = new ArrayList<Shop>();

	private int categoryId = 0, regionId = 0;

	private long taskId;

	SearchLocation location;

	private CharSequence[] items1 = new CharSequence[] { "附近500米", "附近1000米",
			"附近2000米" };

	private CharSequence[] items2 = new CharSequence[] { "距离", "评分", "关注度",
			"有无优惠券", "信息丰富度" };

	private CharSequence[] items3;

	private int typePosition;

	private int rigionItem, typeItem, concernItem = 2;

	private int listType;

	private AsyncTask bitmapTask;

	private int limit = 10, limitStart = 0;

	private boolean loadOver, loading, isCancelled;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.business_list);
		mooerApp = (MooerApplication) getApplication();
		Intent intent = getIntent();
		categoryId = intent.getIntExtra("categoryId", 0);
		regionId = intent.getIntExtra("regionId", 0);
		typePosition = intent.getIntExtra("typePosition", 0);
		rigion = (TextView) findViewById(R.id.rigion);
		type = (TextView) findViewById(R.id.type);
		concern = (TextView) findViewById(R.id.concern);
		title = (TextView) findViewById(R.id.title);
		num = (TextView) findViewById(R.id.business_num);
		rigionButton = (ImageView) findViewById(R.id.rigion_btn);
		typeButton = (ImageView) findViewById(R.id.type_btn);
		concernButton = (ImageView) findViewById(R.id.concern_btn);
		listView = (ListView) findViewById(R.id.listview);
		footer = (ProgressLinearLayout) LayoutInflater.from(this).inflate(
				R.layout.progress_small, null);
		footer.initView();
		listView.addFooterView(footer);
        boolean isNear =  !"搜索".equals(intent.getStringExtra("type1")) && !"搜索".equals(intent.getStringExtra("type2"));
        if(isNear){
		    adapter = new BusinessAdapter(this, shopList, true);
        }else {
            adapter = new BusinessAdapter(this, shopList, false);
        }
		listView.setAdapter(adapter);
		listView.setOnScrollListener(this);

		title.setText(intent.getStringExtra("type1") + "-"
				+ intent.getStringExtra("type2"));
		if (intent.getStringExtra("content") == null) {
			type.setText(intent.getStringExtra("type2"));
		} else {
			type.setText("美食");
		}
		num.setText(getString(R.string.business_num, 0));

		rigionButton.setOnClickListener(this);
		typeButton.setOnClickListener(this);
		concernButton.setOnClickListener(this);
		listView.setOnItemClickListener(this);
		footer.setOnClickListener(this);

		location = new SearchLocation();
		location.setLatitude(mooerApp.getLatitude());
		location.setLongitude(mooerApp.getLongitude());
		location.setSearch(intent.getStringExtra("content") == null ? ""
				: intent.getStringExtra("content"));
		// location.setLatitude(0);
		// location.setLongitude(0);
		location.setRadius(500);
		// location.setRegion(3);
		location.setOrderBy("concern_num");
		location.setCategory(categoryId);
		location.setRegion(regionId);
		if ("搜索".equals(intent.getStringExtra("type1"))) {
			listType = 1;
			if (typePosition == -1) {
				rigion.setText(intent.getStringExtra("type2"));
				type.setText("美食");
				items1 = new CharSequence[] { intent.getStringExtra("type2"),
						"鼓楼区", "白下区", "秦淮区", "玄武区", "建邺区", "下关区", "近郊", "江宁" };
			}else if(typePosition == -2){
                rigion.setText(intent.getStringExtra("type2"));
				type.setText("美食");
				items1 = new CharSequence[] { "新街口商圈", "珠江路商圈", "山西路/湖南路商圈", "南大/南师大商圈", "草场门/龙江商圈", "苜蓿园商圈", "夫子庙商圈"};
            }else {
				rigion.setText("全部地区");
				items1 = new CharSequence[] { "全部地区", "鼓楼区", "白下区", "秦淮区",
						"玄武区", "建邺区", "下关区", "近郊", "江宁" };
			}
			location.setLatitude(0);
			location.setLongitude(0);
			location.setRadius(300000);
		} else {
			if ("搜索".equals(intent.getStringExtra("type2"))) {
				listType = 1;
			} else {
				listType = 0;
			}
		}
		new BusinessListTask(listType).execute(location);
	}

	@Override
	public void onClick(View v) {
		if (v == rigionButton) {
			// showSortWindow("rigion");
			if (items1.length == 9) {
			    showAlertDialog("地区", rigionItem);
			} else if(items1.length == 7){
               showAlertDialog("商圈", rigionItem);
            }
            else {
				showAlertDialog("距离", rigionItem);
			}
		} else if (v == typeButton) {
			showAlertDialog("分类", typeItem);
		} else if (v == concernButton) {
			showAlertDialog("排序", concernItem);
		} else if (v == footer.reload) {
			footer.setVisibility(View.VISIBLE, View.VISIBLE, View.GONE,
					View.GONE);
			new BusinessListTask(listType).execute(location);
		}

	}

	public class BusinessListTask extends
			AsyncTask<SearchLocation, Integer, List<Shop>> {

		private int type; // 0 非搜索 1 搜索

		private boolean isException;

		public BusinessListTask(int type) {
			this.type = type;
		}

		@Override
		protected List<Shop> doInBackground(SearchLocation... location) {
			loading = true;
			List<Shop> list = null;
			try {
				if (type == 0) {
					list = HttpUtils.fetchNearShopList(location[0], limitStart,
							limit);
				} else if (type == 1) {
					list = HttpUtils.fetchShopListByCategory(location[0],
							limitStart, limit);
				}
				for (Shop shop : list) {
					shop.setIcon(mooerApp.getShopListDefaultIcon());
				}
			} catch (Exception e) {
				isException = true;
				e.printStackTrace();
			}
			return list;
		}

		@Override
		protected void onPostExecute(List<Shop> result) {
			super.onPostExecute(result);
			loading = false;
			if (isException) {
				footer.setVisibility(View.GONE, View.GONE, View.VISIBLE,
						View.VISIBLE);
			} else {
				if (result.size() > 0) {
					if (result.size() < limit) {
						listView.removeFooterView(footer);
					}
					shopList.addAll(result);
					adapter.notifyDataSetChanged();
					num.setText(getString(R.string.business_num,
							shopList.size()));
					isCancelled = false;
					bitmapTask = new BitmapTask().execute("");
				} else {
					if (limitStart == 0) {
						footer.setVisibility(View.GONE, View.GONE,
								View.VISIBLE, View.GONE);
						footer.setText(null, "暂无符合条件的商家列表");
						return;
					}
					loadOver = true;
					listView.removeFooterView(footer);
					Log.i(TAG, "ListView load over");
				}
			}
		}

	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		if (shopList.size() > 0) {
			Shop shop = shopList.get(position).copy();
			Intent intent = new Intent(BusinessList.this, Business.class);
			intent.putExtra("businessInfo", shop);
			startActivity(intent);
		}
	}

	private List<String> getList(String type) {
		List<String> list = new ArrayList<String>();
		if ("rigion".equals(type)) {
			list.add("附近500米");
			list.add("附近1000米");
			list.add("附近2000米");
		}
		return list;
	}

	private void showAlertDialog(final String title, int selected) {
		CharSequence[] items = items1;
		if ("距离".equals(title)) {
			items = items1;
		} else if ("排序".equals(title)) {
			items = items2;
		} else if ("分类".equals(title)) {
			if (typePosition != -1) {
				items3 = mooerApp.getBusinessTypes().get(typePosition);
			} else {
				items3 = new CharSequence[Const.types.size() - 1];
				for (int i = 0; i < Const.types.size() - 1; i++) {
					items3[i] = Const.types.get(i);
				}
			}
			items = items3;
		} else if ("地区".equals(title)) {
			items = items1;
		}
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(title);
		builder.setSingleChoiceItems(items, selected,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int item) {

						if ("距离".equals(title)) {
							if (item != rigionItem) {
								rigionItem = item;
								rigion.setText(items1[item]);
								shopList.clear();
								adapter.notifyDataSetChanged();
								listView.removeFooterView(footer);
								footer.setVisibility(View.VISIBLE,
										View.VISIBLE, View.GONE, View.GONE);
								listView.addFooterView(footer);
								num.setText(getString(R.string.business_num, 0));
								if (item == 0) {
									location.setRadius(500);
								} else if (item == 1) {
									location.setRadius(1000);
								} else if (item == 2) {
									location.setRadius(2000);
								}
								limitStart = 0;
								isCancelled = true;
								new BusinessListTask(listType)
										.execute(location);
							}
						} else if ("分类".equals(title)) {
							if (item != typeItem) {
								typeItem = item;
								type.setText(items3[item]);
								shopList.clear();
								adapter.notifyDataSetChanged();
								listView.removeFooterView(footer);
								footer.setVisibility(View.VISIBLE,
										View.VISIBLE, View.GONE, View.GONE);
								listView.addFooterView(footer);
								num.setText(getString(R.string.business_num, 0));
								if (typePosition != -1) {
									String s = mooerApp.getBusinessTypes2()
											.get(typePosition)[item];
									location.setCategory(Integer.parseInt(s));
								} else {
									if (item == 0) {
										location.setCategory(Const.MEISHI);
									} else if (item == 1) {
										location.setCategory(Const.LIREN);
									} else if (item == 2) {
										location.setCategory(Const.HUAJIA);
									} else if (item == 3) {
										location.setCategory(Const.QINZI);
									} else if (item == 4) {
										location.setCategory(Const.JIANSHEN);
									} else if (item == 5) {
										location.setCategory(Const.PEIXUN);
									} else if (item == 6) {
										location.setCategory(Const.YOUXIANYULE);
									} else if (item == 7) {
										location.setCategory(Const.GOUWU);
									} else if (item == 8) {
										location.setCategory(Const.JIUDIAN);
									} else if (item == 9) {
										location.setCategory(Const.SHENGHUOFUWU);
									}
								}
								limitStart = 0;
								isCancelled = true;
								new BusinessListTask(listType)
										.execute(location);
							}

						} else if ("排序".equals(title)) {

							if (item != concernItem) {
								concernItem = item;
								concern.setText(items2[item]);
								shopList.clear();
								adapter.notifyDataSetChanged();
								listView.removeFooterView(footer);
								footer.setVisibility(View.VISIBLE,
										View.VISIBLE, View.GONE, View.GONE);
								listView.addFooterView(footer);
								num.setText(getString(R.string.business_num, 0));
								if (item == 0) {
									location.setOrderBy("distance");
								} else if (item == 1) {
									location.setOrderBy("rating");
								} else if (item == 2) {
									location.setOrderBy("concern_num");
								} else if (item == 3) {
									location.setOrderBy("is_coupon");
								} else if (item == 4) {
									location.setOrderBy("info_num");
								}
								limitStart = 0;
								isCancelled = true;
								new BusinessListTask(listType)
										.execute(location);
							}

						} else if ("地区".equals(title)) {
							if (item != rigionItem) {
								rigionItem = item;
								rigion.setText(items1[item]);
								shopList.clear();
								adapter.notifyDataSetChanged();
								listView.removeFooterView(footer);
								footer.setVisibility(View.VISIBLE,
										View.VISIBLE, View.GONE, View.GONE);
								listView.addFooterView(footer);
								num.setText(getString(R.string.business_num, 0));
								if (item == 0) {
									location.setRegion(0);
								} else if (item == 1) {
									location.setRegion(3);
								} else if (item == 2) {
									location.setRegion(4);
								} else if (item == 3) {
									location.setRegion(15);
								} else if (item == 4) {
									location.setRegion(16);
								} else if (item == 5) {
									location.setRegion(17);
								} else if (item == 6) {
									location.setRegion(18);
								} else if (item == 7) {
									location.setRegion(19);
								} else if (item == 8) {
									location.setRegion(20);
								}
								limitStart = 0;
								isCancelled = true;
								new BusinessListTask(listType)
										.execute(location);
							}
						} else if ("商圈".equals(title)) {
							if (item != rigionItem) {
								rigionItem = item;
								rigion.setText(items1[item]);
								shopList.clear();
								adapter.notifyDataSetChanged();
								listView.removeFooterView(footer);
								footer.setVisibility(View.VISIBLE,
										View.VISIBLE, View.GONE, View.GONE);
								listView.addFooterView(footer);
								num.setText(getString(R.string.business_num, 0));
								if (item == 0) {
									location.setRegion(13);
								} else if (item == 1) {
									location.setRegion(24);
								} else if (item == 2) {
									location.setRegion(6);
								} else if (item == 3) {
									location.setRegion(8);
								} else if (item == 4) {
									location.setRegion(9);
								} else if (item == 5) {
									location.setRegion(10);
								} else if (item == 6) {
									location.setRegion(21);
								}
								limitStart = 0;
								isCancelled = true;
								new BusinessListTask(listType)
										.execute(location);
							}
						}
						dialog.dismiss();
					}
				});
		AlertDialog alert = builder.create();
		alert.show();
	}

	private class BitmapTask extends AsyncTask<String, Integer, String> {

		@Override
		protected String doInBackground(String... params) {
			long id = System.currentTimeMillis();
			taskId = id;
			// 增加一个缓存List避免列表长度变化时遍历发生错误
			List<Shop> cacheList = new ArrayList<Shop>();
			cacheList.addAll(shopList);
			Iterator<Shop> it = cacheList.iterator();
			while (it.hasNext()) {
				/*
				 * 避免重复下载,如果有新的线程,则停止老的线程 当destroy时，停止线程
				 */
				if (id != taskId || isCancelled) {
					break;
				}
				Shop shop = it.next();
				Bitmap icon = null;
				try {
					if (shop.getIcon() == mooerApp.getShopListDefaultIcon()) {
						if (shop.getLogo() != null
								&& !"".equals(shop.getLogo())) {
							icon = HttpUtils.downloadBitmap(shop.getLogo());
							if (icon != null) {
								shop.setIcon(icon);
								publishProgress(0);
							}
						}
					}
				} catch (Exception e) {

				}
			}
			return null;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			adapter.notifyDataSetChanged();
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
			Log.i(TAG, "BitmapTask cancelled");
		}

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (bitmapTask != null) {
			boolean isCancel = bitmapTask.cancel(true);
			Log.i(TAG, "BitmapTask canceled " + isCancel);
			isCancelled = true;
		}
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {

	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		if (shopList.size() == 0) {
			return;
		}
		if (view.getLastVisiblePosition() == view.getCount() - 1) {
			if (view.getCount() < limitStart || loadOver || loading) {
				Log.d(TAG, view.getCount() + "|" + limitStart + "| load over");
				return;
			}
			limitStart = limitStart + limit;
			limit = 5;
			new BusinessListTask(listType).execute(location);
		}
		if (loadOver) {
			listView.removeFooterView(footer);
		}

	}

}
